<?php

namespace App\Admin\Controllers\App;

use App\Admin\Actions\Batches\BatchDisable;
use App\Admin\Actions\Batches\BatchEnable;
use App\Models\Application;
use App\Models\Payment;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;

class PaymentController extends AdminController
{
    protected string $title = '支付管理';

    public function grid(): Grid
    {
        $model = Payment::ofAdmin()
            ->withCount(['orders']);

        return Grid::make($model, function (Grid $grid) {
            $grid->batchActions([
                new BatchEnable(Payment::class),
                new BatchDisable(Payment::class),
            ]);

            if (Admin::user()->isAdministrator()) {
                $grid->column('application.name', '所属应用');
            }
            $grid->column('name', '商户名称');
            $grid->column('mch_id', '商户号');
            $grid->column('can_refund', '退款支持')
                ->bool();
            $grid->column('status')
                ->bool();
            $grid->column('orders_count', '订单数量');
            $grid->column('remark', '备注信息')
                ->textarea();
            $grid->column('created_at');
        });
    }

    public function form(): Form
    {
        return Form::make(Payment::ofAdmin(), function (Form $form) {
            if (Admin::user()->isAdministrator()) {
                $form->select('application_id', '所属应用')
                    ->required()
                    ->options(Application::ofEnabled()->pluck('name', 'id'));
            }
            $form->text('name', '商户名称')
                ->help('支付配置安全域名 '.config('app.url'))
                ->required();
            $form->text('mch_id', '商户号')
                ->required()
                ->help('支付地址 '.route('payments.wechat'));
            $form->text('key_v2', 'V2密钥')
                ->required();
            $form->text('key_v3', 'V3密钥')
                ->required();
            $form->switch('status')
                ->default(true);
            $form->radio('can_refund', '退款支持')
                ->options([
                    0 => '不支持',
                    1 => '支持',
                ])
                ->default(0)
                ->when(1, function (Form $form) {
                    $form->textarea('cert_file', 'API证书')
                        ->rules('required_if:can_refund,1', [
                            'required_if' => '支持退款的微信账户证书必须上传',
                        ])
                        ->help('请粘贴证书内容，切勿修改');
                    $form->textarea('key_file', 'API密钥')
                        ->rules('required_if:can_refund,1', [
                            'required_if' => '支持退款的微信账户证书必须上传',
                        ])
                        ->help('请粘贴证书内容，切勿修改');
                });

            $form->textarea('remark', '备注信息');
        });
    }
}
